package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //登录
     @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1.接收请求处理
        String username = map.get("username");
        String password = map.get("password");

        //2.调用service进行登陆管理
        ResultInfo resultInfo = employeeService.login(username,password);

        //3.如果用户登录成功了，将employ对象保存到session中
         if (resultInfo.getCode()==1){
             Employee employee = (Employee)resultInfo.getData();
             session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
         }

        //4.将结果返回
        return resultInfo;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
         //1.清理session中的用户信息
        session.invalidate();
        //2.返回成功标识
         return ResultInfo.success(null);
    }

    //查询
    @GetMapping("/employee/find")
    public ResultInfo findList(String name){
         List<Employee> employeeList =  employeeService.findByName(name);
         return ResultInfo.success(employeeList);
    }
    //新增
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
         //1.接受的请求参数
        log.info("接受的请求参数是："+employee);
        //2.调用employeeService的save方法
        employeeService.save(employee);
        //3.返回成功结果
        return ResultInfo.success(null);
    }

    //根据ID查询方法
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        ResultInfo resultInfo = employeeService.findById(id);
        return resultInfo;
    }

    //更新
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
         employeeService.update(employee);
        return  ResultInfo.success(null);
    }
}
